package com.example.accessibilitydemo.service;

import java.util.List;

import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.example.accessibilitydemo.util.PreferenceUtil;

/**
 * 微信退出
 * 
 * @author chencq
 *
 */
public class WeChatLoginService extends BaseAccessibilityService {

	private static final String TAG = WeChatLoginService.class.getSimpleName();

	private boolean login = false;
	private String account = "muyan135790", password = "ccq901027";

	@Override
	public void onAccessibilityEvent(AccessibilityEvent event) {
		super.onAccessibilityEvent(event);

		login = PreferenceUtil.getBoolean("login", false);
		int eventType = event.getEventType();

		if (!login)
			return;

		if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
				&& event.getClassName().equals("com.tencent.mm.ui.account.LoginHistoryUI")) {
			delayClickViewByText("更多", 1000);
		} else if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
				&& event.getClassName().equals("com.tencent.mm.ui.base.k")) {
			delayClickViewByText("切换帐号", 1000);
		} else if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
				&& event.getClassName().equals("com.tencent.mm.ui.account.mobile.MobileInputUI")) {
			delayClickViewByText("使用其他方式登录", 1000);
		} else if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
				&& event.getClassName().equals("com.tencent.mm.ui.account.LoginUI")) {
			List<AccessibilityNodeInfo> editNode = findAllViewByID("com.tencent.mm:id/gr");

			AccessibilityNodeInfo accountNode = getEditText(editNode, false);
			AccessibilityNodeInfo pwdNode = getEditText(editNode, true);

			// 输入帐号
			if (accountNode != null) {
				inputText(accountNode, account);
				sleep(1000);
			}

			// 输入密码
			if (pwdNode != null) {
				inputText(pwdNode, password);
				sleep(1000);
			}

			// 点击登录
			AccessibilityNodeInfo loginBtn = findView("com.tencent.mm:id/bbt", "登录");
			performViewClick(loginBtn);

		} else if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
				&& event.getClassName().equals("com.tencent.mm.ui.LauncherUI")) {
			AccessibilityNodeInfo meTab = findView("com.tencent.mm:id/bq0", "我");
			if (meTab != null) {
				Log.i(TAG, "登录成功");
				PreferenceUtil.commitBoolean("login", false);
				performHomeClick();
			}
		}
	}

	public AccessibilityNodeInfo getEditText(List<AccessibilityNodeInfo> editText, boolean isPwd) {
		for (AccessibilityNodeInfo node : editText) {
			// 密码
			if (isPwd && node.isPassword()) {
				return node;
			}
			// 帐号
			if (!isPwd && !node.isPassword()) {
				return node;
			}
		}
		return null;
	}

}
